package com.ruoyi.hr.common.utils;

import com.ruoyi.hr.common.properties.EmailProperties;
import com.ruoyi.hr.domain.HrResume;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Component
public class EmailSender {
	@Autowired
	private EmailProperties emailProperties;

	@Autowired
	private EmailGenerator emailGenerator;

	private Session session;
	/**
	 * 初始化操作
	 */
	@PostConstruct
	private void init(){
		//	账号信息

		//	创建一个配置文件，并保存
		Properties props = new Properties();

		//	SMTP服务器连接信息
		//  126——smtp.126.com
		//  163——smtp.163.com
		//  qqsmtp.qq.com"
		props.put("mail.smtp.host", "smtp.qq.com");//	SMTP主机名
		//  126——25
		//  163——645
		//  qq——456
		props.put("mail.smtp.port", "587");//	主机端口号
		props.put("mail.smtp.auth", "true");//	是否需要用户认证
		props.put("mail.smtp.starttls.enale", "true");//	启用TlS加密

		session = Session.getInstance(props,new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(emailProperties.getAccount(),emailProperties.getCode());
			}
		});
		//  控制台打印调试信息
		session.setDebug(true);
	}


	/**
	 * 发送纯文本消息
	 */
	public void sendTxt(HrResume hrResume){
		String from = emailProperties.getAccount();
		String ack = "http://xxx//hr/resume/isOk/1";
		String reject = "http://xxx//hr/resume/isOk/2";
		try{
			// 获取模板
			String str = emailGenerator.generateEmail(hrResume.getName(), ack, reject);
			//	创建邮件对象
			MimeMessage message = new MimeMessage(session);
			message.setSubject("来自Xxx的Offer");
			message.setText(str);
			message.setFrom(new InternetAddress(from));
			message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(hrResume.getEmail()));
			//	发送
			Transport.send(message);
		}catch (Exception e){
			e.printStackTrace();
		}
	}



}
